<template>
  <view class="container">
    <!-- 身份选择卡片区域 -->
    <view class="identity-selection" v-if="showIdentitySelection">
      <view class="logo-container">
        <view class="title">心理测评系统</view>
        <view class="subtitle">请选择您的身份</view>
      </view>
      
      <view class="identity-cards">
        <!-- 患者身份卡片 -->
        <view class="identity-card" hover-class="card-hover" @click="selectIdentity('patient')" style="z-index: 10;">
          <view class="card-title">患者</view>
          <view class="card-desc">进行心理健康测评</view>
        </view>
        
        <!-- 医生身份卡片 -->
        <view class="identity-card" hover-class="card-hover" @click="selectIdentity('doctor')" style="z-index: 10;">
          <view class="card-title">医生</view>
          <view class="card-desc">管理患者和查看报告</view>
        </view>
        
        <!-- 管理员身份卡片 -->
        <view class="identity-card" hover-class="card-hover" @click="selectIdentity('admin')" style="z-index: 10;">
          <view class="card-title">管理员</view>
          <view class="card-desc">系统管理与统计</view>
        </view>
      </view>
      
      <!-- 登录说明 -->
      <view class="login-notice">
        <view class="notice-text">请选择您的身份进行登录</view>
      </view>
    </view>
    
    <!-- 登录表单区域 -->
    <view class="login-form" v-else>
      <!-- 应用标题 -->
      <view class="logo-container">
        <view class="title">心理测评系统</view>
        <view class="subtitle">{{ getIdentityTitle(selectedIdentity) }}</view>
      </view>
      
      <!-- 动态加载表单内容 -->
      <view class="form-content" :class="getFormClass(selectedIdentity)">
        <!-- 基本信息字段 - 所有用户共用 -->
        <view class="input-group">
          <view class="input-label">真实姓名</view>
          <input class="input" type="text" v-model="real_name" placeholder="请输入真实姓名" maxlength="20" />
        </view>
        
        <view class="input-group">
          <view class="input-label">手机号码</view>
          <input class="input" type="number" v-model="phone" placeholder="请输入手机号码" maxlength="11" />
        </view>
        
            <!-- 患者登录方式切换 -->
        <view v-if="selectedIdentity === 'patient'" class="login-mode-switch">
          <view class="mode-tabs">
            <view 
              class="mode-tab" 
              :class="{ active: patientLoginMode === 'wechat' }"
              @click="patientLoginMode = 'wechat'"
            >
              <text>微信注册</text>
            </view>
            <view 
              class="mode-tab" 
              :class="{ active: patientLoginMode === 'sms' }"
              @click="patientLoginMode = 'sms'"
            >
              <text>验证码登录</text>
            </view>
          </view>
        </view>
        
        <!-- 动态加载身份特有表单 -->
        <view v-if="selectedIdentity === 'patient' && patientLoginMode === 'wechat'" class="patient-form">
          <view class="input-group">
            <view class="input-label">年龄</view>
            <input class="input" type="number" v-model="patientAge" placeholder="请输入年龄" maxlength="3" />
          </view>
          
          <view class="input-group">
            <view class="input-label">性别</view>
            <radio-group class="gender-radio-group" @change="onPatientGenderChange">
              <label class="gender-radio"><radio value="male" :checked="patientGender === 'male'" /> 男</label>
              <label class="gender-radio"><radio value="female" :checked="patientGender === 'female'" /> 女</label>
            </radio-group>
          </view>
          
          <view class="input-group">
            <view class="input-label">身份证号</view>
          <input class="input" type="text" v-model="id_card" placeholder="请输入身份证号" maxlength="18" />
          </view>
        </view>
        
        <!-- 患者验证码登录表单 -->
        <view v-if="selectedIdentity === 'patient' && patientLoginMode === 'sms'" class="sms-login-form">
          <view class="sms-hint">
            <text class="hint-icon">⚠️</text>
            <text class="hint-text-title">仅限医生已建档的患者使用</text>
          </view>
          <view class="sms-hint-sub">
            <text class="hint-text">请使用医生为您建档时填写的手机号+验证码登录</text>
          </view>
          
          <view class="input-group">
            <view class="input-label">验证码</view>
            <view class="code-input-wrapper">
              <input 
                class="input code-input" 
                type="number" 
                v-model="smsCode" 
                placeholder="请输入验证码" 
                maxlength="6"
              />
              <button 
                class="send-code-btn" 
                :class="{ disabled: codeSending || countdown > 0 }"
                :disabled="codeSending || countdown > 0"
                @click="sendSmsCode"
              >
                {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
              </button>
            </view>
          </view>
          
          <view class="dev-hint">
            <text class="dev-text">🔧 开发环境：验证码固定为 123456</text>
          </view>
        </view>
        
        <view v-else-if="selectedIdentity === 'doctor'" class="doctor-form">
          <view class="input-group">
            <view class="input-label">年龄</view>
            <input class="input" type="number" v-model="doctorAge" placeholder="请输入年龄" maxlength="3" />
          </view>
          
          <view class="input-group">
            <view class="input-label">性别</view>
            <radio-group class="gender-radio-group" @change="onDoctorGenderChange">
              <label class="gender-radio"><radio value="male" :checked="doctorGender === 'male'" /> 男</label>
              <label class="gender-radio"><radio value="female" :checked="doctorGender === 'female'" /> 女</label>
            </radio-group>
          </view>
          
          <view class="input-group">
            <view class="input-label">医院</view>
            <input class="input" type="text" v-model="hospital" placeholder="请输入所在医院" maxlength="50" />
          </view>
          
          <view class="input-group">
            <view class="input-label">科室</view>
            <input class="input" type="text" v-model="department" placeholder="请输入所在科室" maxlength="30" />
          </view>
          
          <view class="input-group">
            <view class="input-label">职位</view>
            <input class="input" type="text" v-model="position" placeholder="请输入职位" maxlength="30" />
          </view>
        </view>
        
        <view v-else-if="selectedIdentity === 'admin'" class="admin-form">
          <view class="input-group">
            <view class="input-label">管理员密码</view>
            <view class="password-input">
              <input class="input" :type="showPassword ? 'text' : 'password'" v-model="adminPassword" placeholder="请输入管理员密码" />
              <text class="eye-icon" @tap="togglePassword">
                {{ showPassword ? '👁️🗨️' : '👁️' }}
              </text>
            </view>
          </view>
          
          <view class="admin-notice">
            <text class="notice-text">管理员账户可查看医生信息和医院统计数据</text>
          </view>
        </view>
        

        
        <button class="login-btn" @tap="handleLogin">
          {{ getLoginButtonText() }}
        </button>
        
        <view class="login-options" v-if="pageMode === 'login'">
          <text class="option-text" @tap="register">若无注册，登录自动注册账号</text>
          <text class="option-text" @tap="backToIdentitySelection">重新选择身份</text>
        </view>
      </view>
    </view>
    
    <!-- 微信登录按钮 - 页面最下方，只在身份选择页面显示 -->
    <view class="wechat-login-footer" v-if="showIdentitySelection">
      <div class="divider">
        <text class="divider-text">其他登录方式</text>
      </div>
      <button class="wechat-login-btn" open-type="getUserInfo" @tap="handleWechatLogin">
        <text class="wechat-text">微信授权</text>
      </button>
      <view class="wechat-tip">使用微信账号快速登录，默认以患者身份进入系统</view>
    </view>
  </view>
</template>

<script>
// 请求封装与认证工具
import request from '../../utils/api/request.js';
import { saveToken, saveUserInfo, saveLoginStatus } from '../../utils/auth.js';
import { patientSelfRegister } from '../../utils/api/patient.js';
import { sendSmsCode as sendSmsCodeApi, smsLogin as smsLoginApi } from '../../utils/api/auth.js';

export default {
  data() {
    return {
      // 身份选择状态
      showIdentitySelection: true,
      selectedIdentity: '',
      
      // 页面模式：'login' 登录模式, 'completeProfile' 完善档案模式
      pageMode: 'login',
      
      // 基本信息 - 所有用户共用
      real_name: '',
      phone: '',
      
      // 患者特有信息
      patientAge: '',
      patientGender: 'male',
      id_card: '',
      
      // 患者登录模式：'wechat' 或 'sms'
      patientLoginMode: 'wechat',
      
      // 验证码登录相关
      smsCode: '',
      codeSending: false,
      countdown: 0,
      
      // 医生特有信息
      doctorAge: '',
      doctorGender: 'male',
      hospital: '',
      department: '',
      position: '',
      
      // 管理员特有信息
      adminPassword: '',
      showPassword: false,  // 控制密码显示/隐藏
      loading: false
    };
  },
  
  onLoad(options) {
    console.log('登录页面加载，参数:', options);
    
    // 检查是否是档案完善模式
    if (options.action === 'completeProfile') {
      this.pageMode = 'completeProfile';
      this.selectedIdentity = options.userType || '';
      this.showIdentitySelection = false;
      
      // 预填已有信息
      this.preFillUserInfo();
    }
  },
  methods: {
    // 预填用户信息
    preFillUserInfo() {
      console.log('开始预填用户信息...');
      
      try {
        const userInfo = uni.getStorageSync('userInfo') || {};
        const baseUserInfo = uni.getStorageSync('baseUserInfo') || {};
        const patientInfo = uni.getStorageSync('patientInfo') || {};
        const doctorInfo = uni.getStorageSync('doctorInfo') || {};
        
        console.log('本地存储的用户信息:', { userInfo, baseUserInfo, patientInfo, doctorInfo });
        
        // 预填基本信息
        this.real_name = userInfo.nickname || baseUserInfo.wechat_name || '';
        this.phone = userInfo.phone || baseUserInfo.phone || '';
        
        // 根据用户类型预填特定信息
        if (this.selectedIdentity === 'patient') {
          this.patientAge = patientInfo.age || userInfo.age || '';
          this.patientGender = patientInfo.gender === 0 ? 'female' : 'male';
          this.id_card = patientInfo.id_card || userInfo.id_card || userInfo.idCard || '';
        } else if (this.selectedIdentity === 'doctor') {
          this.doctorAge = userInfo.age || '';
          this.doctorGender = userInfo.gender === 'female' ? 'female' : 'male';
          this.hospital = doctorInfo.hospital || userInfo.hospital || '';
          this.department = doctorInfo.department || userInfo.department || '';
          this.position = doctorInfo.position || userInfo.position || '';
        }
        
        console.log('预填完成:', {
          real_name: this.real_name,
          phone: this.phone,
          patientAge: this.patientAge,
          hospital: this.hospital
        });
        
      } catch (error) {
        console.error('预填用户信息失败:', error);
      }
    },
    
    // 选择身份
    selectIdentity(identity) {
      console.log('选择身份:', identity);
      this.selectedIdentity = identity;
      this.showIdentitySelection = false;
      // 强制刷新UI
      this.$forceUpdate();
    },
    
    // 返回身份选择
    backToIdentitySelection() {
      this.showIdentitySelection = true;
      this.selectedIdentity = '';
    },
    
    // 获取身份标题
    getIdentityTitle(identity) {
      switch(identity) {
        case 'patient':
          return '患者登录';
        case 'doctor':
          return '医生登录';
        case 'admin':
          return '管理员登录';
        default:
          return '';
      }
    },
    
    // 获取表单样式类
    getFormClass(identity) {
      switch(identity) {
        case 'patient':
          return 'patient-form';
        case 'doctor':
          return 'doctor-form';
        case 'admin':
          return 'admin-form';
        default:
          return '';
      }
    },
    
    // 患者性别变更
    onPatientGenderChange(e) {
      this.patientGender = e.detail.value;
    },
    
    // 医生性别变更
    onDoctorGenderChange(e) {
      this.doctorGender = e.detail.value;
    },
    
    // 切换密码显示/隐藏
    togglePassword() {
      this.showPassword = !this.showPassword;
    },
    
    // 获取微信用户信息
    async getWechatUserProfile() {
      return new Promise((resolve, reject) => {
        uni.getUserProfile({
          desc: '用于完善用户资料',
          success: res => resolve(res.userInfo),
          fail: err => reject(err)
        });
      });
    },
    
    // 获取微信登录code
    async getWechatCode() {
      return new Promise((resolve, reject) => {
        uni.login({
          success: res => {
            if (res.code) {
              resolve(res.code);
            } else {
              reject(new Error('获取code失败'));
            }
          },
          fail: err => reject(err)
        });
      });
    },

    
    // 登录诊断工具（开发调试用）
    async diagnoseLogin() {
      console.log('========================================');
      console.log('===== 🔍 开始登录诊断 =====');
      console.log('========================================');
      
      // 1. 检查网络
      console.log('\n[诊断1] 检查网络连接...');
      uni.getNetworkType({
        success: (res) => {
          console.log('✅ 网络类型:', res.networkType);
          if (res.networkType === 'none') {
            console.error('❌ 网络未连接');
            uni.showToast({ title: '网络未连接，请检查网络', icon: 'none' });
          }
        },
        fail: () => {
          console.error('❌ 无法获取网络状态');
        }
      });
      
      // 2. 检查微信授权
      console.log('\n[诊断2] 测试微信授权...');
      try {
        const code = await this.getWechatCode();
        console.log('✅ 微信授权成功');
        console.log('   Code:', code.substring(0, 15) + '...');
      } catch (error) {
        console.error('❌ 微信授权失败:', error);
      }
      
      // 3. 检查后端连接
      console.log('\n[诊断3] 测试后端连接...');
      try {
        // 尝试一个简单的GET请求
        const testResp = await request.get('/auth/user-info');
        if (testResp) {
          console.log('✅ 后端连接正常');
          console.log('   响应码:', testResp.code);
        }
      } catch (error) {
        console.error('❌ 后端连接失败:', error);
        console.error('   错误信息:', error.message || error.errMsg);
      }
      
      // 4. 检查本地存储
      console.log('\n[诊断4] 检查本地存储...');
      const storageInfo = {
        token: uni.getStorageSync('token'),
        userInfo: uni.getStorageSync('userInfo'),
        userType: uni.getStorageSync('userType'),
        isLoggedIn: uni.getStorageSync('isLoggedIn'),
        patientTempInfo: uni.getStorageSync('patientTempInfo')
      };
      
      console.log('存储状态:');
      console.log('  - Token:', storageInfo.token ? '✅ 已设置 (' + storageInfo.token.substring(0, 20) + '...)' : '❌ 未设置');
      console.log('  - 用户信息:', storageInfo.userInfo ? '✅ 已设置' : '❌ 未设置');
      console.log('  - 用户类型:', storageInfo.userType || '❌ 未设置');
      console.log('  - 登录状态:', storageInfo.isLoggedIn ? '✅ 已登录' : '❌ 未登录');
      
      console.log('\n========================================');
      console.log('===== ✅ 诊断完成 =====');
      console.log('========================================');
      
      uni.showModal({
        title: '诊断完成',
        content: '请查看控制台了解详细信息。如有问题，请截图控制台日志反馈。',
        showCancel: false
      });
    },
    
    // 登录（增强版：更好的错误处理和容错能力）
    async login() {
      console.log('\n========================================');
      console.log('===== 🔑 开始登录流程 =====');
      console.log('身份类型:', this.selectedIdentity);
      console.log('页面模式:', this.pageMode);
      console.log('========================================\n');
      
      // 如果是档案完善模式，直接完善档案
      if (this.pageMode === 'completeProfile') {
        await this.completeProfile();
        return;
      }
      
      // 根据不同身份进行不同的验证
      if (this.selectedIdentity === 'patient') {
        // 患者验证
        if (!this.real_name) {
          uni.showToast({ title: '请输入真实姓名', icon: 'none' });
          return;
        }
        
        if (!this.patientAge || isNaN(this.patientAge) || this.patientAge < 0 || this.patientAge > 120) {
          uni.showToast({ title: '请输入有效的年龄', icon: 'none' });
          return;
        }
        
        if (!this.id_card) {
          uni.showToast({ title: '请输入身份证号', icon: 'none' });
          return;
        }
        
        // 身份证号验证（测试版：放宽限制）
        const idCardReg = /^[\dXx]{6,18}$/;
        if (!idCardReg.test(this.id_card)) {
          uni.showToast({ title: '请输入6-18位的身份证号', icon: 'none' });
          return;
        }
      } else if (this.selectedIdentity === 'doctor') {
        // 医生验证
        if (!this.real_name) {
          uni.showToast({ title: '请输入真实姓名', icon: 'none' });
          return;
        }
        
        if (!this.doctorAge || isNaN(this.doctorAge) || this.doctorAge < 0 || this.doctorAge > 120) {
          uni.showToast({ title: '请输入有效的年龄', icon: 'none' });
          return;
        }
        
        if (!this.hospital) {
          uni.showToast({ title: '请输入所在医院', icon: 'none' });
          return;
        }
        
        if (!this.department) {
          uni.showToast({ title: '请输入所在科室', icon: 'none' });
          return;
        }
        
        if (!this.position) {
          uni.showToast({ title: '请输入职位', icon: 'none' });
          return;
        }
      } else if (this.selectedIdentity === 'admin') {
        // 管理员验证
        if (!this.real_name) {
          uni.showToast({ title: '请输入真实姓名', icon: 'none' });
          return;
        }
        
        if (!this.adminPassword) {
          uni.showToast({ title: '请输入管理密码', icon: 'none' });
          return;
        }
        // 注意：密码验证将由后端处理，前端不再验证具体密码值
      }
      
      // 通用验证
      if (!this.phone) {
        uni.showToast({ title: '请输入手机号码', icon: 'none' });
        return;
      }
      
      // 手机号格式验证
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.phone)) {
        uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
        return;
      }
      
      this.loading = true;
      let loginStep = 0; // 记录登录进度

      try {
        // ========== 步骤1：获取微信授权 ==========
        loginStep = 1;
        console.log('[步骤1/6] 开始获取微信授权...');
        let userProfile, code;
        try {
          userProfile = await this.getWechatUserProfile();
          code = await this.getWechatCode();
          console.log('✅ 步骤1完成：微信授权成功');
          console.log('   - 昵称:', userProfile.nickName);
          console.log('   - Code:', code.substring(0, 15) + '...');
        } catch (error) {
          console.error('❌ 步骤1失败：微信授权失败', error);
          throw new Error('微信授权失败：' + (error.errMsg || '用户拒绝授权或网络问题'));
        }

        // ========== 步骤2：后端登录 ==========
        loginStep = 2;
        console.log('\n[步骤2/6] 调用后端登录接口...');
        let loginResp;
        try {
          loginResp = await request.post('/auth/login', {
            code: code,
            user_info: {
              nickName: userProfile.nickName,
              avatarUrl: userProfile.avatarUrl
            }
          });
          
          if (!loginResp || loginResp.code !== 200 || !loginResp.data || !loginResp.data.token) {
            throw new Error(loginResp?.msg || '登录接口返回异常');
          }
          
          saveToken(loginResp.data.token);
          console.log('✅ 步骤2完成：后端登录成功');
          console.log('   - Token已保存:', loginResp.data.token.substring(0, 20) + '...');
        } catch (error) {
          console.error('❌ 步骤2失败：后端登录失败', error);
          throw new Error('后端登录失败：' + (error.message || '服务器连接失败'));
        }

        // ========== 步骤3：完善用户信息 ==========
        loginStep = 3;
        console.log('\n[步骤3/6] 完善用户基础信息...');
        try {
          const roleMap = { 'patient': 2, 'doctor': 1, 'admin': 3 };
          const completeResp = await request.post('/auth/complete-info', {
            phone: this.phone,
            role: roleMap[this.selectedIdentity]
          });
          
          if (!completeResp || completeResp.code !== 200) {
            console.warn('⚠️  步骤3警告：完善信息失败，但继续登录流程');
            console.warn('   - 错误信息:', completeResp?.msg);
          } else {
            console.log('✅ 步骤3完成：用户信息完善');
            console.log('   - 手机号:', this.phone);
            console.log('   - 角色:', this.selectedIdentity);
          }
        } catch (error) {
          console.warn('⚠️  步骤3警告：完善信息失败', error.message, '但继续登录流程');
          // 不抛出错误，允许继续
        }

        // ========== 步骤4：身份特定处理 ==========
        loginStep = 4;
        console.log('\n[步骤4/6] 处理身份特定信息...');
        try {
          if (this.selectedIdentity === 'patient') {
            const genderNum = this.patientGender === 'male' ? 1 : 0;
            
            // 调用患者自主建档接口
            try {
              const registerResp = await patientSelfRegister({
                real_name: this.real_name,
                age: parseInt(this.patientAge),
                gender: genderNum,
                id_card: this.id_card,
                phone: this.phone
              });
              
              if (registerResp && registerResp.code === 200) {
                console.log('✅ 步骤4完成：患者自主建档成功');
                console.log('   - 姓名:', this.real_name);
                console.log('   - 年龄:', this.patientAge);
                console.log('   - 性别:', this.patientGender);
                console.log('   - 身份证:', this.id_card);
                console.log('   - 患者ID:', registerResp.data.patient_id);
              } else {
                console.warn('⚠️  步骤4警告：患者建档失败，但继续登录');
                console.warn('   - 错误信息:', registerResp?.msg);
              }
            } catch (error) {
              console.warn('⚠️  步骤4警告：患者建档失败', error.message, '但继续登录流程');
            }
            
          } else if (this.selectedIdentity === 'doctor') {
            const doctorResp = await request.post('/users/doctor', {
              phone: this.phone,
              real_name: this.real_name,
              hospital: this.hospital,
              department: this.department,
              position: this.position
            });
            
            if (doctorResp && doctorResp.code === 200) {
              console.log('✅ 步骤4完成：医生档案创建成功');
              console.log('   - 医院:', this.hospital);
              console.log('   - 科室:', this.department);
              console.log('   - 职位:', this.position);
            } else {
              console.warn('⚠️  步骤4警告：医生建档失败，但继续登录');
              console.warn('   - 错误信息:', doctorResp?.msg);
            }
          } else {
            console.log('✅ 步骤4完成：管理员无需建档');
          }
        } catch (error) {
          console.warn('⚠️  步骤4警告：身份处理失败', error.message, '但继续登录流程');
          // 不抛出错误，允许继续
        }

        // ========== 步骤5：获取用户完整信息 ==========
        loginStep = 5;
        console.log('\n[步骤5/6] 获取用户完整信息...');
        try {
          const userInfoResp = await request.get('/auth/user-info');
          if (userInfoResp && userInfoResp.code === 200 && userInfoResp.data) {
            saveUserInfo(userInfoResp.data);
            saveLoginStatus(true, this.selectedIdentity, userInfoResp.data);
            console.log('✅ 步骤5完成：用户信息已获取并保存');
            console.log('   - 用户ID:', userInfoResp.data.id);
            console.log('   - 角色:', userInfoResp.data.role);
          } else {
            console.warn('⚠️  步骤5警告：获取用户信息失败，使用本地信息');
            saveLoginStatus(true, this.selectedIdentity);
          }
        } catch (error) {
          console.warn('⚠️  步骤5警告：获取用户信息失败', error.message);
          // 尝试使用已有信息
          saveLoginStatus(true, this.selectedIdentity);
        }

        // ========== 步骤6：跳转到首页 ==========
        loginStep = 6;
        console.log('\n[步骤6/6] 准备跳转到首页...');
        uni.showToast({ 
          title: this.selectedIdentity === 'patient' ? '登录成功，档案已创建' : '登录成功', 
          icon: 'success',
          duration: 1500
        });
        
        setTimeout(() => {
          const targetUrl = `/pages/index/index?userType=${this.selectedIdentity}`;
          console.log('✅ 步骤6完成：跳转到', targetUrl);
          uni.redirectTo({
            url: targetUrl,
            fail: (err) => {
              console.warn('⚠️  redirectTo失败，尝试switchTab', err);
              uni.switchTab({
                url: '/pages/index/index',
                fail: (err2) => {
                  console.error('❌ switchTab也失败了', err2);
                }
              });
            }
          });
        }, 1500);
        
        console.log('\n========================================');
        console.log('===== ✅ 登录流程全部完成 =====');
        console.log('========================================\n');
        
      } catch (error) {
        console.error('\n========================================');
        console.error('===== ❌ 登录失败 =====');
        console.error('失败位置：步骤', loginStep);
        console.error('错误详情:', error);
        console.error('========================================\n');
        
        let errorMsg = '登录失败，请重试';
        let errorDetail = '';
        
        // 根据失败步骤提供更详细的错误信息
        switch(loginStep) {
          case 1:
            errorMsg = '微信授权失败';
            errorDetail = '请确保允许微信授权，或检查网络连接';
            break;
          case 2:
            errorMsg = '服务器连接失败';
            errorDetail = '请检查网络连接，或稍后重试';
            break;
          case 3:
            errorMsg = '用户信息设置失败';
            errorDetail = '请联系管理员';
            break;
          default:
            errorMsg = error.message || '未知错误';
            errorDetail = '请截图控制台日志反馈';
        }
        
        if (error && error.errMsg) {
          errorDetail = error.errMsg;
        } else if (error && error.message) {
          errorDetail = error.message;
        }
        
        // 显示错误提示
        uni.showModal({
          title: errorMsg,
          content: errorDetail,
          showCancel: false,
          confirmText: '我知道了'
        });
        
      } finally {
        this.loading = false;
      }
    },
    
    // 完善档案
    async completeProfile() {
      console.log('\n========================================');
      console.log('===== 📝 开始完善档案 =====');
      console.log('用户类型:', this.selectedIdentity);
      console.log('========================================\n');
      
      this.loading = true;
      
      try {
        // 表单验证
        if (!this.validateForm()) {
          return;
        }
        
        // 根据用户类型完善档案
        if (this.selectedIdentity === 'patient') {
          await this.completePatientProfile();
        } else if (this.selectedIdentity === 'doctor') {
          await this.completeDoctorProfile();
        }
        
        // 完善成功后跳转到对应页面
        uni.showToast({ 
          title: '档案完善成功', 
          icon: 'success',
          duration: 1500
        });
        
        setTimeout(() => {
          const targetUrl = this.selectedIdentity === 'doctor' 
            ? '/pages/doctor/patientList' 
            : '/pages/index/index';
          
          console.log('档案完善成功，跳转到:', targetUrl);
          
          // 检查目标页面是否为 TabBar 页面
          const tabBarPages = [
            'pages/index/index',
            'pages/chaKanBaoGao/chaKanBaoGao',
            'pages/userCenter/userCenter'
          ];
          
          if (tabBarPages.includes(targetUrl.replace(/^\//, ''))) {
            // TabBar 页面使用 switchTab
            console.log('✅ 使用 switchTab 跳转到 TabBar 页面:', targetUrl);
            uni.switchTab({
              url: targetUrl,
              fail: () => {
                console.log('⚠️ switchTab 失败，使用 redirectTo 作为备选');
                uni.redirectTo({ url: targetUrl });
              }
            });
          } else {
            // 非 TabBar 页面使用 redirectTo
            console.log('✅ 使用 redirectTo 跳转到非 TabBar 页面:', targetUrl);
            uni.redirectTo({ url: targetUrl });
          }
        }, 1500);
        
      } catch (error) {
        console.error('完善档案失败:', error);
        uni.showToast({
          title: error.message || '完善档案失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 表单验证
    validateForm() {
      if (!this.real_name) {
        uni.showToast({ title: '请输入真实姓名', icon: 'none' });
        return false;
      }
      
      if (!this.phone) {
        uni.showToast({ title: '请输入手机号码', icon: 'none' });
        return false;
      }
      
      // 手机号格式验证
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.phone)) {
        uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
        return false;
      }
      
      if (this.selectedIdentity === 'patient') {
        if (!this.patientAge || isNaN(this.patientAge) || this.patientAge < 0 || this.patientAge > 120) {
          uni.showToast({ title: '请输入有效的年龄', icon: 'none' });
          return false;
        }
        
        if (!this.id_card) {
          uni.showToast({ title: '请输入身份证号', icon: 'none' });
          return false;
        }
        
        // 身份证号验证（测试版：放宽限制）
        const idCardReg = /^[\dXx]{6,18}$/;
        if (!idCardReg.test(this.id_card)) {
          uni.showToast({ title: '请输入6-18位的身份证号', icon: 'none' });
          return false;
        }
      } else if (this.selectedIdentity === 'doctor') {
        if (!this.doctorAge || isNaN(this.doctorAge) || this.doctorAge < 0 || this.doctorAge > 120) {
          uni.showToast({ title: '请输入有效的年龄', icon: 'none' });
          return false;
        }
        
        if (!this.hospital) {
          uni.showToast({ title: '请输入所在医院', icon: 'none' });
          return false;
        }
        
        if (!this.department) {
          uni.showToast({ title: '请输入所在科室', icon: 'none' });
          return false;
        }
        
        if (!this.position) {
          uni.showToast({ title: '请输入职位', icon: 'none' });
          return false;
        }
      }
      
      return true;
    },
    
    // 完善患者档案
    async completePatientProfile() {
      console.log('完善患者档案...');
      
      const genderNum = this.patientGender === 'male' ? 1 : 2;
      
      const registerResp = await patientSelfRegister({
        real_name: this.real_name,
        age: parseInt(this.patientAge),
        gender: genderNum,
        id_card: this.id_card,
        phone: this.phone
      });
      
      if (registerResp && registerResp.code === 200) {
        console.log('患者档案完善成功:', registerResp.data);
        
        // 更新本地存储
        const patientInfo = {
          user_id: registerResp.data.patient_id,
          gender: genderNum,
          age: parseInt(this.patientAge),
          id_card: this.id_card
        };
        uni.setStorageSync('patientInfo', patientInfo);
        
        // 更新用户信息
        const userInfo = uni.getStorageSync('userInfo') || {};
        userInfo.nickname = this.real_name;
        userInfo.age = parseInt(this.patientAge);
        userInfo.gender = this.patientGender;
        userInfo.id_card = this.id_card;
        userInfo.idCard = this.id_card;
        uni.setStorageSync('userInfo', userInfo);
        
      } else {
        throw new Error(registerResp?.msg || '患者档案完善失败');
      }
    },
    
    // 完善医生档案
    async completeDoctorProfile() {
      console.log('完善医生档案...');
      
      const doctorResp = await request.post('/users/doctor', {
        phone: this.phone,
        real_name: this.real_name,
        hospital: this.hospital,
        department: this.department,
        position: this.position
      });
      
      if (doctorResp && doctorResp.code === 200) {
        console.log('医生档案完善成功:', doctorResp.data);
        
        // 更新本地存储
        const doctorInfo = {
          user_id: doctorResp.data.doctor_id,
          hospital: this.hospital,
          department: this.department,
          position: this.position
        };
        uni.setStorageSync('doctorInfo', doctorInfo);
        
        // 更新用户信息
        const userInfo = uni.getStorageSync('userInfo') || {};
        userInfo.nickname = this.real_name;
        userInfo.age = parseInt(this.doctorAge);
        userInfo.gender = this.doctorGender;
        userInfo.hospital = this.hospital;
        userInfo.department = this.department;
        userInfo.position = this.position;
        uni.setStorageSync('userInfo', userInfo);
        
      } else {
        throw new Error(doctorResp?.msg || '医生档案完善失败');
      }
    },
    
    // 注册账号
    register() {
      // 这里应该是跳转到注册页面
      console.log('注册账号');
      uni.showToast({ title: '注册功能待实现', icon: 'none' });
    },
    
    // 微信登录处理
    async handleWechatLogin() {
      console.log('点击微信授权登录');
      // 检查是否选择了身份
      if (!this.selectedIdentity) {
        uni.showToast({
          title: '请先选择用户身份',
          icon: 'none'
        });
        return;
      }

      try {
        // 添加加载提示
        uni.showLoading({
          title: '正在授权登录...'
        });
        
        // 1. 先获取用户信息（必须在点击事件中直接调用）
        const userProfile = await new Promise((resolve, reject) => {
          uni.getUserProfile({
            desc: '用于完善用户资料',
            success: res => resolve(res.userInfo),
            fail: err => reject(err)
          });
        });
        
        console.log('获取用户信息成功:', userProfile);
        
        // 2. 然后获取微信登录code
        const loginRes = await new Promise((resolve, reject) => {
          uni.login({
            success: res => resolve(res),
            fail: err => reject(err)
          });
        });
        
        const { code } = loginRes;
        console.log('获取到的微信登录code:', code);
        
        if (!code) {
          console.error('未获取到有效的code');
          uni.hideLoading();
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
          return;
        }
        
        // 3. 准备微信登录参数
        const nickname = userProfile.nickName;
        const avatarUrl = userProfile.avatarUrl;
        
        // 准备微信登录参数对象
        const wechatLoginParams = {
          code: code,
          nickname: nickname,
          avatarUrl: avatarUrl,
          identity: this.selectedIdentity
        };
        
        console.log('准备发送到API层的微信登录数据:', wechatLoginParams);
        
        // 定义重试函数
        const loginWithRetry = async (attempt = 1) => {
          try {
            // 使用doLogin便捷方法完成微信登录流程
            const loginResult = await doLogin(
              wechatLogin,
              wechatLoginParams
            );
            
            console.log('微信登录成功:', loginResult);
            uni.hideLoading();
            
            // 处理登录成功逻辑
            if (loginResult.code === 200 || loginResult.success) {
              // 保存token和用户信息
              const { token, user } = loginResult.data || {};
              if (token) {
                saveToken(token);
              }
              if (user) {
                uni.setStorageSync('userInfo', user);
              }
              
              // 获取用户登录状态
              const loginStatus = getLoginStatus();
              console.log('微信登录成功，用户类型:', loginStatus.userType);
              
              // 跳转到首页，带上用户类型参数
              uni.redirectTo({
                url: '/pages/index/index?userType=' + loginStatus.userType,
                success: () => {
                  console.log('微信登录成功，已跳转到首页');
                  uni.showToast({
                    title: '登录成功',
                    icon: 'success'
                  });
                },
                fail: (err) => {
                  console.error('跳转失败:', err);
                  uni.showToast({
                    title: '跳转失败，请重试',
                    icon: 'none'
                  });
                }
              });
            } else {
              uni.showToast({
                title: loginResult.msg || '登录失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error(`微信登录失败(第${attempt}次):`, error);
            
            // 如果是网络错误且重试次数小于3，进行重试
            const maxRetries = 2;
            if (attempt <= maxRetries && 
                error && 
                (error.errMsg && (error.errMsg.includes('network') || 
                                  error.errMsg.includes('timeout') ||
                                  error.errMsg.includes('certificate')))) {
              
              // 计算退避时间（指数退避）
              const delay = Math.pow(2, attempt) * 500;
              console.log(`将在${delay}ms后重试...`);
              
              await new Promise(resolve => setTimeout(resolve, delay));
              return loginWithRetry(attempt + 1);
            } else {
              uni.hideLoading();
              // 显示具体错误信息
              let errorMsg = '登录失败，请重试';
              if (error && error.msg) {
                errorMsg = error.msg;
              } else if (error && error.errMsg) {
                errorMsg = error.errMsg;
              }
              
              uni.showToast({
                title: errorMsg,
                icon: 'none'
              });
            }
          }
        };
        
        // 开始首次登录尝试
        await loginWithRetry();
        
      } catch (error) {
        uni.hideLoading();
        console.error('微信登录失败:', error);
        
        // 如果是用户取消授权
        if (error.errMsg && error.errMsg.includes('auth deny')) {
          uni.showToast({ title: '需要授权才能登录', icon: 'none' });
        } else {
          uni.showToast({ title: '获取用户信息失败，请重试', icon: 'none' });
        }
      }
    },
    
    // ========== 验证码登录相关方法 ==========
    
    // 统一登录入口
    handleLogin() {
      // 如果是患者且选择了验证码登录模式
      if (this.selectedIdentity === 'patient' && this.patientLoginMode === 'sms') {
        this.handleSmsLogin();
      } else {
        // 其他情况走原来的登录逻辑
        this.login();
      }
    },
    
    // 获取登录按钮文本
    getLoginButtonText() {
      if (this.pageMode === 'completeProfile') {
        return '完善档案';
      }
      if (this.selectedIdentity === 'patient' && this.patientLoginMode === 'sms') {
        return '验证码登录';
      }
      return '登录';
    },
    
    // 发送验证码
    async sendSmsCode() {
      // 验证手机号
      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return;
      }
      
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
      
      try {
        this.codeSending = true;
        console.log('[验证码登录] 发送验证码:', this.phone);
        
        const response = await sendSmsCodeApi(this.phone);
        console.log('[验证码登录] 发送响应:', response);
        
        if (response.code === 200) {
          uni.showToast({
            title: '验证码：123456（开发环境）',
            icon: 'none',
            duration: 3000
          });
          
          // 开始倒计时
          this.countdown = 60;
          const timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        } else {
          throw new Error(response.msg || '发送失败');
        }
      } catch (error) {
        console.error('[验证码登录] 发送失败:', error);
        uni.showToast({
          title: error.message || '发送失败，请重试',
          icon: 'none'
        });
      } finally {
        this.codeSending = false;
      }
    },
    
    // 验证码登录
    async handleSmsLogin() {
      // 验证输入
      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return;
      }
      
      if (!this.smsCode) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        });
        return;
      }
      
      try {
        this.loading = true;
        console.log('[验证码登录] 开始登录:', { phone: this.phone, code: this.smsCode });
        
        const response = await smsLoginApi(this.phone, this.smsCode);
        console.log('[验证码登录] 登录响应:', response);
        
        if (response.code === 200 && response.data) {
          // 保存token和用户信息
          saveToken(response.data.token);
          saveUserInfo(response.data.user);
          saveLoginStatus(true, 'patient', response.data.user);
          
          console.log('[验证码登录] 登录成功，用户信息已保存');
          
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          });
          
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index'
            });
          }, 1500);
        } else if (response.code === 201 && response.data && response.data.need_register) {
          // 手机号未注册
          uni.showModal({
            title: '提示',
            content: '该手机号尚未注册，请先通过微信注册或联系医生创建账号',
            showCancel: false,
            confirmText: '知道了',
            success: (res) => {
              if (res.confirm) {
                // 切换回微信注册模式
                this.patientLoginMode = 'wechat';
              }
            }
          });
        } else {
          throw new Error(response.msg || '登录失败');
        }
      } catch (error) {
        console.error('[验证码登录] 登录失败:', error);
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

/* 身份选择区域样式 */
.identity-selection {
  flex: 1;
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 登录说明样式 */
.login-notice {
  margin-top: 40rpx;
  text-align: center;
  padding: 20rpx;
}

.notice-text {
  font-size: 26rpx;
  color: #666;
}

.identity-selection .logo-container {
  align-items: center;
  margin-bottom: 80rpx;
  text-align: center;
}

.subtitle {
  font-size: 28rpx;
  color: #666;
  margin-top: 20rpx;
}

.identity-cards {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  padding: 20rpx;
}

.identity-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  text-align: center;
  transition: all 0.3s ease;
  border: 2rpx solid transparent;
}

.identity-card:active {
  transform: scale(0.98);
  background-color: #f0f0f0;
}

.identity-card:hover {
  border-color: #2db5a3;
}

/* 底部微信登录按钮样式 */
    .wechat-login-footer {
      padding: 40rpx;
      text-align: center;
      margin-top: auto;
    }
    
    .divider {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
    }
    
    .divider::before, .divider::after {
      content: '';
      flex: 1;
      height: 1rpx;
      background-color: #ddd;
    }
    
    .divider-text {
      padding: 0 20rpx;
      color: #999;
      font-size: 26rpx;
    }

    .wechat-tip {
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #999;
      text-align: center;
    }

    /* 微信登录相关样式 */
    .wechat-login-container {
      margin-top: 40rpx;
      width: 100%;
    }

.wechat-login-btn {
  background-color: #07c160;
  color: #fff;
  border-radius: 8rpx;
  margin-top: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wechat-icon {
  margin-right: 10rpx;
  font-size: 40rpx;
}

.wechat-text {
  font-size: 32rpx;
}

.card-hover {
  border-color: #2db5a3;
  background-color: #f8f8f8;
}

/* 确保身份选择区域在最上层 */
.identity-selection {
  z-index: 100;
}

.card-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.card-desc {
  font-size: 26rpx;
  color: #666;
}

/* 登录表单样式 */
.login-form {
  flex: 1;
  padding: 40rpx;
  display: flex;
  flex-direction: column;
}

.logo-container {
  align-items: center;
  margin-bottom: 60rpx;
  padding-top: 60rpx;
  text-align: center;
}

.logo {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-content {
  flex: 1;
}

/* 患者表单特殊样式 */
.patient-form {
  background: transparent;
  padding: 20rpx;
}

/* 医生表单特殊样式 */
.doctor-form {
  background: transparent;
  padding: 20rpx;
}

/* 管理员表单特殊样式 */
.admin-form {
  background: transparent;
  padding: 20rpx;
}

.input-group {
  margin-bottom: 40rpx;
}

.input-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.input {
  width: 100%;
  height: 88rpx;
  background-color: transparent;
  border: none;
  border-bottom: 2rpx solid #ddd;
  padding: 0 30rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  transition: border-bottom-color 0.3s ease;
}

.input:focus {
  border-bottom-color: #2db5a3;
  outline: none;
}

.password-input {
  position: relative;
  background-color: transparent;
}

.eye-icon {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 36rpx;
}

.login-btn {
  width: 100%;
  height: 88rpx;
  background-color: #2db5a3;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  margin-top: 60rpx;
}

.login-options {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
  padding: 0 20rpx;
  flex-wrap: wrap;
}

.option-text {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: inline-block;
}

/* 性别选择器样式 */
.gender-radio-group {
  display: flex;
  justify-content: space-around;
}

.gender-radio {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

.third-party-login {
  margin-top: 60rpx;
  text-align: center;
}

.third-party-title {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 40rpx;
  position: relative;
}

.third-party-title::before,
.third-party-title::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 100rpx;
  height: 1px;
  background-color: #ddd;
}

.third-party-title::before {
  left: 60rpx;
}

.third-party-title::after {
  right: 60rpx;
}

.third-party-icons {
  display: flex;
  justify-content: center;
}

.icon-item {
  margin: 0 40rpx;
}

.icon {
  font-size: 28rpx;
  color: #666;
}

.wechat-phone-btn {
  margin-top: 30rpx;
  background-color: #07C160;
  color: #fff;
  font-size: 28rpx;
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  border: none;
}

.wechat-phone-btn:active {
  background-color: #06B258;
}

/* 登录模式切换 */
.login-mode-switch {
  margin: 20rpx 0 30rpx 0;
}

.mode-tabs {
  display: flex;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 6rpx;
  gap: 6rpx;
}

.mode-tab {
  flex: 1;
  height: 64rpx;
  line-height: 64rpx;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

.mode-tab.active {
  background: #fff;
  color: #2db5a3;
  font-weight: bold;
  box-shadow: 0 2rpx 8rpx rgba(45, 181, 163, 0.15);
}

/* 验证码登录表单 */
.sms-login-form {
  background: transparent;
  padding: 20rpx 0;
}

.sms-hint {
  display: flex;
  align-items: center;
  padding: 20rpx 24rpx;
  background: linear-gradient(135deg, #FFF3E0 0%, #FFE0B2 100%);
  border-radius: 12rpx 12rpx 0 0;
  border-left: 4rpx solid #FF9800;
}

.sms-hint-sub {
  padding: 16rpx 24rpx 20rpx;
  background: linear-gradient(135deg, #FFF8E1 0%, #FFF3E0 100%);
  border-radius: 0 0 12rpx 12rpx;
  border-left: 4rpx solid #FFC107;
  margin-bottom: 30rpx;
}

.hint-icon {
  font-size: 32rpx;
  margin-right: 12rpx;
}

.hint-text-title {
  flex: 1;
  font-size: 28rpx;
  color: #E65100;
  font-weight: bold;
  line-height: 1.4;
}

.hint-text {
  flex: 1;
  font-size: 24rpx;
  color: #F57C00;
  line-height: 1.5;
}

.code-input-wrapper {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  width: 200rpx;
  height: 60rpx;
  line-height: 60rpx;
  background: linear-gradient(135deg, #2db5a3 0%, #1e8e7e 100%);
  color: white;
  font-size: 24rpx;
  border-radius: 8rpx;
  padding: 0;
  border: none;
  box-shadow: 0 2rpx 8rpx rgba(45, 181, 163, 0.3);
}

.send-code-btn::after {
  border: none;
}

.send-code-btn.disabled,
.send-code-btn:disabled {
  background: #ccc;
  box-shadow: none;
}

.dev-hint {
  margin-top: 20rpx;
  padding: 15rpx 20rpx;
  background: #FFF3E0;
  border-radius: 8rpx;
  border-left: 4rpx solid #FF9800;
}

.dev-text {
  font-size: 24rpx;
  color: #E65100;
  line-height: 1.5;
}
</style>